﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理;
using SmartProduction.Domain.客户管理.WorkOrder;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.work_SalesOrderCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.work_SalesOrderHandler
{
    public class work_SalesOrderQueryCommandHandler : IRequestHandler<work_SalesOrderQueryCommand, APIResult<APIPaing<work_SalesOrder>>>
    {
        /// <summary>
        /// 销售订单仓储
        /// </summary>
        private readonly IBaseRepository<APIResult<work_SalesOrder>> salesRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="salesRepository">销售订单仓储</param>
        /// <param name="mapper">映射</param>
        public work_SalesOrderQueryCommandHandler(IBaseRepository<APIResult<work_SalesOrder>> salesRepository,IMapper mapper)
        {
            this.salesRepository = salesRepository;
            this.mapper = mapper;
        }


        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<APIResult<APIPaing<work_SalesOrder>>> Handle(work_SalesOrderQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaing<work_SalesOrder>> result = new APIResult<APIPaing<work_SalesOrder>>();
                result.Code = APIEnums.查询成功;
                result.Msg = APIEnums.查询成功.ToString();
                var list = salesRepository.GetAll().Result;
                if (!string.IsNullOrEmpty(request.OrderCode))
                {
                    list = list.Where(x => x.OrderCode == request.OrderCode);
                }
                if (!string.IsNullOrEmpty(request.OrderSubject))
                {
                    list = list.Where(x => x.OrderSubject == request.OrderSubject);
                }

                var count = list.Count();
                var page = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                var models = list.OrderByDescending(x => x.work_SalesOrderId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                APIPaing<work_SalesOrder> paging = new APIPaing<work_SalesOrder>();
                paging.PageCount = page;
                paging.TotalCount = count;
                paging.Items = mapper.Map<List<work_SalesOrder>>(models);
                result.data = paging;
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
